import { reqGetGoodsDetail ,reqAddCar,reqDelectCart,reqChangeSatuas} from '@/api'
import {getUUID} from '@/utils/uuid_token'
const state = {
  // 初始值
  goodsDetail: {},
  // 游客id
  uuid_token:getUUID()
};
const mutations = {
  GETGOODSDETAIL(state,goodsDetail){
    state.goodsDetail = goodsDetail
  },
  // ADDCAR(state)
};
const actions = {
  async getGoodsDetail(context, id) { 
    let res = await reqGetGoodsDetail(id)
    if (res.code == 200) {
      context.commit('GETGOODSDETAIL', res.data)
    }
  }, 
  async addCar(_,{id,num}){
    let res = await reqAddCar(id,num)
    console.log("hahah",id,num);
    // 因为这里没有返回data,所以利用async返回的Promise结果来判断成功还是失败
    if (res.code == 200) {
      return 'ok!'
    }else {
      return Promise.reject(new Error('失败了！'))
    }
  },
  async delectCart(context,id){
    let res = await reqDelectCart(id)
    if (res.code == 200) {
      return 'ok!'
    }else {
      return Promise.reject(new Error('失败了！'))
    }
  },
  async changeSatuas(context,{id,isChecked}){
    let res = await reqChangeSatuas(id,isChecked)
    if (res.code == 200) {
      return 'ok!'
    }else {
      return Promise.reject(new Error('失败了！'))
    }
  },
  async delectAll({dispatch,getters}){
    // 获取全部的产品 
      console.log(getters.shopList.cartInfoList);
      let promiseAll = []
      getters.shopList.cartInfoList.forEach(item=>{
        let promise =  item.isChecked == 1 ? dispatch('delectCart',item.skuId) : '';
        promiseAll.push(promise)
      })
      return Promise.all(promiseAll)
  },
  async updateAllChecked({dispatch,getters},isChecked){
    let promiseAll = []
    console.log(getters);
    getters.shopList.cartInfoList.forEach(item=>{
      let promise = dispatch('changeSatuas',{id:item.skuId,isChecked:isChecked})
      promiseAll.push(promise)
    })
    return Promise.all(promiseAll)
  }
};
const getters = {
  categoryView(state){
    return state.goodsDetail.categoryView || {}
  },
  skuInfo(state){
    return state.goodsDetail.skuInfo || {}
  },
  spuSaleAttrList(state){
    return state.goodsDetail.spuSaleAttrList || []
  }
};
export default {
  state,
  mutations,
  actions,
  getters
}